package com.aote.rs;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import net.javacrumbs.json2xml.JsonXmlReader;
import org.xml.sax.InputSource;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.xml.XppReader;

/**
 * Usage: Add the following two gradle dependencies
 * 		"com.thoughtworks.xstream:xstream:1.3",
		"net.javacrumbs:json-xml:4.1", 
 * @author LGY
 *
 */

public class XmlJsonTranslator {
	
	/**
	 * xml to json
	 * @param xml
	 * @return
	 * @throws Exception
	 */
	public String xml2Json(String xml) throws Exception
	{
        HierarchicalStreamReader sourceReader = new XppReader(new StringReader(xml));

        StringWriter buffer = new StringWriter();
        JettisonMappedXmlDriver jettisonDriver = new JettisonMappedXmlDriver();
        jettisonDriver.createWriter(buffer);
        HierarchicalStreamWriter destinationWriter = jettisonDriver.createWriter(buffer);

        HierarchicalStreamCopier copier = new HierarchicalStreamCopier();
        copier.copy(sourceReader, destinationWriter);
        return buffer.toString();
    }
	
	/**
	 * json to xml
	 * @param json
	 * @param namespace 名字空间， 不写传null
	 * @param root xml要求必须有根，如果无根，添加一个，否则为空
	 * @return
	 */
	public String json2Xml(String json, String namespace, String root) throws Exception
	{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        InputSource source = new InputSource(new StringReader(json));
        Result result = new StreamResult(out);
        transformer.transform(new SAXSource(new JsonXmlReader(namespace, false, root), source), result);
        return new String(out.toByteArray());
	}

	
	public static void main(String[] args) throws Exception
	{
		XmlJsonTranslator sjt = new XmlJsonTranslator();
		String xml = sjt.json2Xml("{\"a\":1, \"b\":\"2\", \"c\":[{\"a\":1},{\"a\":1}]}", null, "asd");
		System.out.println(xml);
		String json = sjt.xml2Json(xml);
		System.out.println(json);
	}
}
